<template>
  <a-modal
      title="添加用户"
      width="1200px"
      v-model:visible="state.visible"
      :confirm-loading="loading"
      @ok="handleOk"
      @cancel="state.visible = false"
  >
    <a-table
        :loading="loading"
        :columns="columns"
        :data-source="list"
        :pagination="pagination"
        @change="handleChange"
        row-key="id"
        :custom-row="customRow"
        :row-selection="rowSelection"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'userType'">
          {{ $filters.dictText(record.userType, 'USER_TYPE') }}
        </template>
        <template v-if="column.dataIndex === 'sex'">
          {{ $filters.dictText(record.sex, 'sex') }}
        </template>
        <template v-if="column.dataIndex === 'status'">
          {{ $filters.dictText(record.status, 'USER_STATUS') }}
        </template>
      </template>
    </a-table>
  </a-modal>
</template>

<script lang="ts" setup>
import { getUsers } from '@/api/sys-user'
import { computed, reactive } from 'vue'
import { PageParam } from '@/config/common'
import { saveUserRole } from '@/api/sys-role'
import { message } from 'ant-design-vue'
import { usePagination } from '@/modules/use-modules'

interface State {
  visible: boolean
  roleId: string
  selectedRowKeys: string[]
}

const state = reactive<State>({
  visible: false,
  roleId: '',
  selectedRowKeys: []
})

const columns = [
  {
    title: '账号',
    dataIndex: 'username'
  },
  {
    title: '昵称',
    dataIndex: 'nickName'
  },
  {
    title: '学校',
    dataIndex: 'schoolName'
  },
  {
    title: '状态',
    dataIndex: 'status'
  }
]

const {
  pagination,
  loading,
  list,
  handleChange,
  loadData
} = usePagination<any>((page: PageParam) => {
  return getUsers(page, { withoutRoleId: state.roleId })
})

const open = (roleId: string) => {
  state.roleId = roleId
  state.visible = true
  loadData()
}

const rowSelection = computed(() => {
  return {
    selectedRowKeys: state.selectedRowKeys,
    onChange: (selectedRowKeys: any) => {
      state.selectedRowKeys = selectedRowKeys
    }
  }
})

const handleOk = () => {
  const userIds = state.selectedRowKeys
  saveUserRole(userIds, state.roleId).then(() => {
    message.success('操作成功')
    state.visible = false
    emits('ok')
  })
}

const selectRow = (record: { [key: string]: any }) => {
  const selectedRowKeys = [...state.selectedRowKeys]
  if (selectedRowKeys.indexOf(record.id) >= 0) {
    selectedRowKeys.splice(selectedRowKeys.indexOf(record.id), 1)
  } else {
    selectedRowKeys.push(record.id)
  }
  state.selectedRowKeys = selectedRowKeys
}

const customRow = (record: any) => {
  return {
    onClick: (event: any) => {
      selectRow(record)
    }
  }
}

defineExpose({ open })
const emits = defineEmits(['ok'])

</script>
